package com.free.bsf.eureka.client.limitrate.provider;
import com.free.bsf.core.base.LimitRateException;
import com.free.bsf.core.util.ReflectionUtils;
import com.free.bsf.core.util.StringUtils;

public class ProviderFactory {
    private static Object lock= new Object();
    private static BaseProvider redisProvider;
    private static BaseProvider localProvider;
    public static BaseProvider create(String provider){
        if("redis".equalsIgnoreCase(provider)){
            if(redisProvider==null) {
                redisProvider = create(redisProvider, ProviderFactory.class.getPackage().getName() + ".RedisProvider");
            }
            return redisProvider;
        }else if("local".equalsIgnoreCase(provider)){
            if(localProvider==null){
                localProvider = create(localProvider, ProviderFactory.class.getPackage().getName() + ".LocalProvider");
            }
            return localProvider;
        }
        throw new LimitRateException("未找到provider="+ StringUtils.nullToEmpty(provider));
    }

    private static BaseProvider create(BaseProvider provider,String className){
        if(provider!=null)
            return provider;
        synchronized (lock){
            if(provider!=null)
                return provider;
            try {
                provider = (BaseProvider)ReflectionUtils.tryClassForName(className).newInstance();
                return provider;
            }catch (Exception exp){
                throw new LimitRateException("未找到provider class:"+ StringUtils.nullToEmpty(className));
            }
        }
    }
}
